<template>
    <div class="operateArea">
        <a-button type="primary" @click="showAddModel" class="queryBtn" :loading="loading">
            新增
        </a-button>
    </div>

    <div class="category-detail-container">
        <a-spin tip="Loading..." :spinning="isLoading">
            <div class="oneCategory">
                <a-card v-for="(item, index) in cookbookCategoryList" :key="index" :title="item.name"
                    style="margin-bottom: 20px;">
                    <template #extra>
                        <a class="editContainer" @click="showEditModel(item)">
                            <EditFilled />
                        </a>
                        <a class="delContainer">
                            <DeleteFilled @click="handleDel(item)" />
                        </a>
                    </template>
                    <a-card-grid class="oneCategoryCard" v-for="(subItem, index) in item.children" :key="index"
                        @click="handleClick(item, subItem)">{{
                            subItem.name
                        }}</a-card-grid>
                </a-card>
            </div>
        </a-spin>
    </div>

    <!-- 编辑 -->
    <a-modal v-model:open="editModel" title="编辑分类" @ok="handleEdit">
        <template #footer>
            <a-button class="cancelBtn" key="back" @click="editModel = false">{{ $t('common.cancel') }}</a-button>
            <a-button class="confirmBtn" key="submit" type="primary" :loading="loading" @click="handleEdit">{{
                $t('common.confirm') }}</a-button>
        </template>
        <a-form ref="formRef" :model="editAddRecord" :rules="rules">
            <a-form-item label="分类" name="name">
                <a-input v-model:value="editAddRecord.name" />
            </a-form-item>

            <a-form-item label="子类别" name="ingredient">
                <div class="ingredientSelect" v-for="(item, index) in editAddRecord.children" :key="index">
                    <div class="ingredientInput">
                        <a-form-item-rest>
                            <a-input v-model:value="item.name" />
                        </a-form-item-rest>
                    </div>

                    <div class="ingredientAddSub">
                        <MinusOutlined class="subOper" @click="subInput(index, item)" />
                        <PlusOutlined v-if="editAddRecord.children.length - 1 === index" class="addOper"
                            @click="addInput(0)" />
                        <PlusOutlined v-else style="color: #fff;" />
                    </div>
                </div>
            </a-form-item>
        </a-form>
    </a-modal>

    <!-- 新增 -->
    <a-modal v-model:open="addModel" title="添加分类" @ok="handleAdd">
        <template #footer>
            <a-button class="cancelBtn" key="back" @click="addModel = false">{{ $t('common.cancel') }}</a-button>
            <a-button class="confirmBtn" key="submit" type="primary" :loading="loading" @click="handleAdd">{{
                $t('common.confirm') }}</a-button>
        </template>
        <a-form ref="formRef" :model="editAddRecord" :rules="rules">
            <a-form-item label="分类" name="name">
                <a-input v-model:value="editAddRecord.name" />
            </a-form-item>

            <a-form-item label="子类别" name="ingredient">
                <div class="ingredientSelect" v-for="(item, index) in editAddRecord.children" :key="index">
                    <div class="ingredientInput">
                        <a-form-item-rest>
                            <a-input v-model:value="item.name" />
                        </a-form-item-rest>
                    </div>

                    <div class="ingredientAddSub">
                        <MinusOutlined class="subOper" @click="subInput(index, item)" />
                        <PlusOutlined v-if="editAddRecord.children.length - 1 === index" class="addOper"
                            @click="addInput(0)" />
                        <PlusOutlined v-else style="color: #fff;" />
                    </div>
                </div>
            </a-form-item>
        </a-form>
    </a-modal>
</template>

<script setup>
import { addCookbookCategory, deleteCookbookCategory, editCookbookCategory, findCookbookCategoryList } from '@/api/cookbookCategory.js';
import router from '@/router';
import { ExclamationCircleOutlined } from '@ant-design/icons-vue';
import { Modal, message } from 'ant-design-vue';
import { createVNode, onMounted, reactive, ref } from 'vue';
import { useRoute } from 'vue-router';

const route = useRoute();
// 编辑框
const editModel = ref(false);
// 新增框
const addModel = ref(false);
// 响应式数据
const isLoading = ref(true);
// 分类列表数据
const cookbookCategoryList = ref([]);
// 加载
const loading = ref(false);
const editAddRecord = reactive({
    id: null,
    name: null,
    children: [],
    parentId: -1,
});
// 规则校验
const rules = {
    name: [
        {
            required: true,
            message: '请输入分类名称',
            trigger: 'change',
        },
    ],
};

// 获取难度对应的颜色
const getDifficultyColor = (difficulty) => {
    const colors = {
        '简单': 'green',
        '中等': 'orange',
        '困难': 'red'
    };
    return colors[difficulty] || 'blue';
};
// 展示编辑框
const showEditModel = (item) => {
    editModel.value = true;
    editAddRecord.id = item.id;
    editAddRecord.children = JSON.parse(JSON.stringify(item.children));
    editAddRecord.name = item.name;
    console.log(editAddRecord);
}
// 展示新增框
const showAddModel = () => {
    addModel.value = true;
    editAddRecord.id = null;
    editAddRecord.children = [{ name: null }];
    editAddRecord.name = null;
}
// 删除
const handleDel = (item) => {
    Modal.confirm({
        title: '系统消息',
        icon: createVNode(ExclamationCircleOutlined),
        content: `确定要删除 ${item.name} 分类吗?`,
        okText: '是',
        okType: 'danger',
        cancelText: '否',
        onOk() {
            deleteCookbookCategory(item.id).then(res => {
                if (res.code === 200) {
                    message.success('删除成功');
                    fetchCategoryDetail();
                }
            });
        },
        onCancel() {
        },
    });
}
// 编辑
const handleEdit = () => {
    if (!editAddRecord.name) {
        message.error('分类名称不能为空');
        return;
    }
    let children = editAddRecord.children;
    console.log(children);
    for (let index in children) {
        let item = children[index];
        if (!item.name) {
            message.error('子分类名称不能为空');
            return;
        }
    }
    editCookbookCategory(editAddRecord).then(res => {
        if (res.code === 200) {
            console.log(res.data);
            editModel.value = false;
            message.success('编辑成功');
            fetchCategoryDetail();
        }
    })
}
// 新增
const handleAdd = () => {
    let children = editAddRecord.children;
    for (let index in children) {
        let item = children[index];
        if (!item.name) {
            message.error('子分类名称不能为空');
            return;
        }
    }
    addCookbookCategory(editAddRecord).then(res => {
        if (res.code === 200) {
            console.log(res.data);
            editModel.value = false;
            message.success('添加成功');
            fetchCategoryDetail();
        }
    })
}
// 获取分类详情
const fetchCategoryDetail = async () => {
    try {
        isLoading.value = true;
        const response = await findCookbookCategoryList();
        if (response.code === 200) {
            console.log(response.data);
            cookbookCategoryList.value = response.data;
            if (response.data.children.length <= 0) {
                cookbookCategoryList.children.value = [{ name: null, id: null }];
            }
        }
    } catch (error) {
    } finally {
        isLoading.value = false;
    }
};

onMounted(() => {
    fetchCategoryDetail();
});

// 删除分类
const subInput = (index) => {
    if (editAddRecord.children.length < 2) {
        return;
    }
    editAddRecord.children.splice(index, 1);
}
// 添加分类
const addInput = () => {
    editAddRecord.children.push({
        id: null,
        name: null,
    });
}
const handleClick = (item, subItem) => {
    router.push({
        path: '/cookbook-manage/cookbook-list',
        query: {
            parentId: item.id,
            subId: subItem.id,
        },
    });
}
</script>

<style scoped lang="scss">
.category-detail-container {
    // max-width: 1200px;
    margin: 0 auto;
    // padding: 24px;

    .oneCategory {
        padding: 30px;
        background-color: #fff;

        .oneCategoryCard {
            width: 25%;
            text-align: center;
            cursor: pointer;
        }

        .delContainer,
        .editContainer {
            color: #529739;
        }

        .editContainer {
            margin-right: 10px;
        }

        .delContainer:hover {
            color: green;
        }

        .editContainer:hover {
            color: green;
        }
    }
}

.category-info {
    display: flex;
    gap: 24px;
}

.cover-image {
    flex-shrink: 0;
    width: 300px;
    height: 200px;
    border-radius: 8px;
    overflow: hidden;
}

.cover-image img {
    width: 100%;
    height: 100%;
    object-fit: cover;
}

.info-content {
    flex: 1;
}

.info-content h2 {
    margin: 0 0 16px 0;
    font-size: 24px;
    color: rgba(0, 0, 0, 0.85);
}

.description {
    color: rgba(0, 0, 0, 0.65);
    line-height: 1.6;
    margin-bottom: 16px;
}

.meta-info {
    display: flex;
    gap: 8px;
}

@media (max-width: 768px) {
    .category-info {
        flex-direction: column;
    }

    .cover-image {
        width: 100%;
        height: auto;
        aspect-ratio: 16/9;
    }
}

.ingredientSelect {
    display: flex;
    margin-bottom: 5px;
    width: 100%;

    .ingredientInput {
        display: flex;
        width: 100%;
        align-items: center;
    }

    .ingredientAddSub {
        display: flex;
        justify-content: center;
        align-items: center;

        .subOper {
            color: grey;
            margin-left: 10px;
            margin-right: 6px;
            cursor: pointer;
        }

        .addOper {
            color: green;
            cursor: pointer;
        }
    }
}

.operateArea {
    background-color: #fff;
    display: flex;
    align-items: center;
    justify-content: end;
    padding: 20px 20px 20px 0px;
    border-bottom: 1px solid #d9d9d9;
}
</style>